import datetime

from formencode import validators as V
from formencode import Schema
from formencode.validators import *

class RangeBoundNumber(FancyValidator):

    _messages = dict(
        toosmall='must be greater than %(min)s',
        toobig='must be less than %(max)s')

    def __init__(self, base, min, max):
        self.base, self.min, self.max = base, min, max

    def _to_python(self, value, state):
        num = self.base.to_python(value, state)
        if self._min is not None and num < self._min :
            raise Invalid(self.message('toosmall'))
        if self._max is not None and num > self._max:
            raise Invalid(self.message('toobig'))
        return num

class TimeConverter(V.TimeConverter):

    def _to_python(self, value, state):
        tup = V.TimeConverter._to_python(self, value, state)
        return datetime.time(*tup)

class DictMaker(object):
    def to_python(self, value, state=None):
        if not value: return {}
        else: return value
    def from_python(self, value, state=None):
        if not value: return {}
        else: return value

class RegexValidator(V.Regex):

    def message(self, msg, state):
        if msg == 'invalid':
            return self.invalid_message
        else:
            return fe.Regex.message(self, msg)

class ModelValidator(FancyValidator):

    _messages = dict(
        notfound='The object with key %s could not be found')

    def __init__(self, cls):
        from sqlalchemy.orm import class_mapper
        self.mapper = class_mapper(cls)

    def _from_python(self, value, state):
        import pdb; pdb.set_trace()
        return self.mapper.key_for(value)

    def _to_python(self, value, state):
        import pdb; pdb.set_trace()
        return self.mapper.get(value)
